/**
 *
 */
package net.oschina.git.haxteam.zrank.rank;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import net.oschina.git.haxteam.zrank.api.PlayerData;
import net.oschina.git.haxteam.zrank.jdbc.UserInfoManager;
import net.oschina.git.haxteam.zrank.main.Main;

/**
 * @author qq996
 *
 */
public class PlayerLevelUp {

	static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");

	//需要多少经验升级
	public int PlayerLevelUpneedXp(String playername){
		String level = UserInfoManager.getUserLevel(playername);
		String formula = Main.config.getString("等级.经验公式");
		try {
			return (Integer) jse.eval(formula.replaceAll("level",level));
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}

	//升级
	public void LevelUp(String playername){
		PlayerData.setLevel(playername, PlayerData.getLevel(playername)+1);
	}

	//获得经验
	public void addXp(String playername,int addxp){
		PlayerData.setXp(playername, PlayerData.getXp(playername)+addxp);
		while(true){
			if(PlayerData.getXp(playername) >= PlayerLevelUpneedXp(playername)){
				LevelUp(playername);
			}else{
				return;
			}
		}
	}

}
